<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
    <!-- 表单组件 el-form，通过 label-width 设置 label 的宽度  -->
    <!-- 匿名插槽 -->
    <!-- //!#1 定义 ref -->
    <el-form ref="formRef" v-loading="loading" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @focus="getEmployeeSimple">
          <el-option v-for="item in peoples" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog 有专门放置底部操作栏的插槽，具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为 24 -->
      <el-col :span="6">
        <!-- //!#2 点击确定按钮，兜底校验成功后调用添加接口 -->
        <el-button type="primary" size="small" :loading="loading" @click="btnOK">确定</el-button>
        <el-button size="small" @click="closeDialog">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import { getDepartments, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  name: 'AddDept',
  // data() {
  //   return {
  //     showDialog: false
  //   }
  // }
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    treeNode: {
      type: Object,
      default: null
    }
  },
  data() {
    const checkName = async(_, value, callback) => {
      const { depts } = await getDepartments()
      // 支持编辑的校验
      let isRepeat = false
      if (this.formData.id) {
        // !编辑
        // 输入的内容 value 不能和兄弟重复，所以找兄弟，特点是：从所有的数据里面找，谁的 pid 等于我的（treeNode.id 或 formData.id） pid
        // 注意要把自己排除掉
        // 再从兄弟里面看一下有没有 name 和我的是一样的
        isRepeat = depts.filter(item => item.pid === this.treeNode.pid && item.id !== this.treeNode.id).some(item => item.name === value)
      } else {
        // !添加
        isRepeat = depts.filter(item => item.pid === this.treeNode.id).some(item => item.name === value)
      }
      isRepeat ? callback(new Error(`当前部门下已经有重复的 ${value}`)) : callback()
    }
    const checkCode = async(_, value, callback) => {
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.formData.id) {
        // !编辑，要把自己排除掉
        isRepeat = depts.some(item => item.code === value && item.id !== this.treeNode.id)
      } else {
        isRepeat = depts.some(item => item.code === value)
      }
      isRepeat ? callback(new Error(`当前已存在${value}编码`)) : callback()
    }
    return {
      // 定义表单数据
      formData: {
        name: '', // 部门名称，必填 1-50 个字符，同级部门中禁止出现重复部门
        code: '', // 部门编码，必填 1-50 个字符，部门编码在整个模块中都不允许重复
        manager: '', // 部门管理者，必填
        introduce: '' // 部门介绍，必填 1-300 个字符
      },
      // 定义校验规则
      rules: {
        name: [{
          required: true,
          message: '部门名称不能为空',
          trigger: 'blur'
        },
        {
          min: 1,
          max: 50,
          message: '部门名称要求1-50个字符',
          trigger: 'blur'
        },
        {
          validator: checkName,
          trigger: 'blur'
        }
        ],
        code: [{
          required: true,
          message: '部门编码不能为空',
          trigger: 'blur'
        },
        {
          min: 1,
          max: 50,
          message: '部门编码要求1-50个字符',
          trigger: 'blur'
        },
        {
          validator: checkCode,
          trigger: 'blur'
        }
        ],
        manager: [{
          required: true,
          message: '部门负责人不能为空',
          trigger: 'blur'
        }],
        introduce: [{
          required: true,
          message: '部门介绍不能为空',
          trigger: 'blur'
        },
        {
          trigger: 'blur',
          min: 1,
          max: 300,
          message: '部门介绍要求1-50个字符'
        }
        ]
      },
      peoples: [],
      loading: false
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑部门' : '添加部门'
    }
  },
  methods: {
    async getEmployeeSimple() {
      const peoples = await getEmployeeSimple()
      this.peoples = peoples
    },
    btnOK() {
      this.$refs.formRef.validate(async isValid => {
        if (isValid) {
          if (this.formData.id) {
            // !编辑
            await updateDepartments(this.formData)
          } else {
            // 新增
            // 仅仅是后端添加成功了
            await addDepartments({
              ...this.formData,
              pid: this.treeNode.id
            })
          }
          this.$emit('addDepts')
          this.$emit('update:showDialog', false)
        }
      })
    },
    closeDialog() {
      // 直接手动的重置一下
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      // !重置校验规则，只有和表单绑定过的数据才能进行重置
      this.$refs.formRef.resetFields()
      // 点关闭按钮和遮罩会触发
      this.$emit('update:showDialog', false)
    },
    async getDepartDetail(id) {
      this.loading = true
      const depts = await getDepartDetail(id)
      // 因为 formData 是响应式的，所以一旦赋值就会自动进行填充
      this.formData = depts
      this.loading = false
    }
  }
}
</script>
